package net.unix8.thrift.server;

import java.util.ArrayList;

import org.apache.thrift.TException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import static org.elasticsearch.index.query.QueryBuilders.*;
public class HelloWorldServiceImpl implements HelloWorldService.Iface {

	public HelloWorldServiceImpl() {
	}

	@Override
	public String sayHello(String username) throws TException {
		return "Hi," + username + " welcome to my blog www.unix8.net";
	}
	public Result searchInfos(String key, SearchType type) throws org.apache.thrift.TException{
		
		ArrayList infos = new ArrayList(); 
		infos.add("RENZHENWEN1");
		infos.add("RENZHENWEN2");
		infos.add("RENZHENWEN3");
		infos.add("RENZHENWEN4");
		Result result = new Result();
		result.setSize(99);
		result.setState(ResponseState.StateOk);
		result.setInfos(infos);
		
		
		
		
		try {
            Client client = TransportClient.builder().build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
           
            QueryBuilder qb1 = termQuery("a", "menu");
            QueryBuilder qb2= QueryBuilders.multiMatchQuery("git", "name","人员");
            

            SearchResponse response = client.prepareSearch("myindex").setTypes("mytype").setQuery(qb1).execute()
                    .actionGet();
           //System.out.println("STA:"+response.status());
            	
            SearchHits hits = response.getHits();
            if (hits.totalHits() > 0) {
                for (SearchHit hit : hits) {
                    System.out.println("score:"+hit.getScore()+":\t"+hit.getSource());// .get("title")
                }
            } else {
                System.out.println("搜到0条结果");
            }

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

		return result;
	}

}